/* eslint-disable */
import Oidc from 'oidc-client'
import 'babel-polyfill'
var host = configUrl.frontEndUrl
var mgr = new Oidc.UserManager({
	authority: configUrl.crmUrl, //CRM 登录地址 'http://192.168.1.173:9010/',
	client_id: configUrl.client_id,
	post_logout_redirect_uri: host + '/index.html',
	redirect_uri: host + '/oidc/login-callback.html',
	silent_redirect_uri: host + '/oidc/refresh-token.html',
	accessTokenExpiringNotificationTime: 4,
	automaticSilentRenew: true,
	response_type: 'id_token token',
	// scope: 'openid profile api-cloudpacs api-telemed api-idcas api-operate api-reserve api-quality',
	scope: 'openid profile api-cloudpacs api-telemed api-idcas api-operate api-reserve api-quality',
	filterProtocolClaims: true,
	loadUserInfo: true
})

Oidc.Log.logger = console
Oidc.Log.level = Oidc.Log.INFO

mgr.events.addUserLoaded(function (user) {
	// console.log('New User Loaded：', arguments);
	// console.log('Acess_token: ', user.access_token)
	mgr.getUser()
})

mgr.events.addAccessTokenExpiring(function () {
	// console.log('AccessToken Expiring：', arguments);
})

mgr.events.addAccessTokenExpired(function () {
	// console.log('AccessToken Expired：', arguments);
})
mgr.events.addSilentRenewError(function () {
	console.error('Silent Renew Error：', arguments)
})

mgr.events.addUserSignedOut(function () {
	// console.log('UserSignedOut：', arguments);
	mgr.signoutRedirect().then(function (resp) {}).catch(function (err) {})
})

export default class SecurityService {
	// Redirect of the current window to the authorization endpoint.
	signIn () {
		mgr.signinRedirect({ state: window.location.href }).catch(function (err) {
			console.log(err)
		})
	}

	// Redirect of the current window to the end session endpoint
	signOut () {
		mgr
			.signoutRedirect()
			.then(function (resp) {
				console.log('signed out', resp)
			})
			.catch(function (err) {
				console.log(err)
			})
	}
	// Get the user roles logged in
	getRole () {
		let self = this
		return new Promise((resolve, reject) => {
			mgr
				.getUser()
				.then(function (user) {
					console.log('user' + user)
					if (user == null) {
						self.signIn()
						return resolve(null)
					}
					else {
						return resolve(user)
					}
				})
				.catch(function (err) {
					console.log(err)
					return reject(err)
				})
		})
	}
}
